const TextToSpeechView = {
    name: 'TextToSpeechView',
    props: {
        settings: {
            type: Object,
            default: () => ({
                model: 'cogtts',
                voice: 'tongtong',
                response_format: 'wav'
            })
        }
    },
    data() {
        return {
            inputText: '',
            audioUrl: null,
            loading: false,
            isPlaying: false,
            error: null
        };
    },
    computed: {
        // 计算属性：判断是否有有效音频
        hasValidAudio() {
            return !!this.audioUrl && this.audioUrl.trim() !== '';
        }
    },
    methods: {
        async submit() {
            if (!this.inputText.trim()) {
                this.error = '请输入要转换的文字';
                return;
            }
            
            this.loading = true;
            this.error = null;
            this.audioUrl = null;
            this.isPlaying = false;
            
            try {
                const result = await apiClient.textToSpeech(this.inputText.trim(), null, this.settings);
                
                if (result.success) {
                    // 使用返回的audio_url
                    const audioUrl = result.data.audio_url;
                    if (audioUrl.startsWith('/')) {
                        // 相对路径，转换为完整URL
                        this.audioUrl = `${window.location.origin}${audioUrl}`;
                    } else {
                        this.audioUrl = audioUrl;
                    }
                    
                    // 清空输入框
                    this.inputText = '';
                    this.$message.success('语音生成成功！');
                } else {
                    this.error = result.error || '文字转语音失败';
                }
            } catch (error) {
                console.error('文字转语音失败:', error);
                const errorInfo = window.ErrorHandler ? window.ErrorHandler.formatError(error) : { message: error.message || '未知错误' };
                this.error = errorInfo.message;
                if (errorInfo.suggestion) {
                    this.$message.warning(errorInfo.suggestion);
                }
            } finally {
                this.loading = false;
            }
        },
        // 手动控制播放
        playAudio() {
            if (!this.hasValidAudio) return;
            
            const audioEl = this.$refs.audioRef;
            if (audioEl) {
                audioEl.play().then(() => {
                    this.isPlaying = true;
                }).catch(error => {
                    console.error('播放失败:', error);
                    this.$message.error('音频播放失败，请重试');
                    this.isPlaying = false;
                });
            }
        },
        // 手动控制暂停
        pauseAudio() {
            const audioEl = this.$refs.audioRef;
            if (audioEl) {
                audioEl.pause();
                this.isPlaying = false;
            }
        },
        // 音频播放结束回调
        onAudioEnded() {
            this.isPlaying = false;
        },
        // 下载音频
        downloadAudio() {
            if (!this.hasValidAudio) return;
            
            fetch(this.audioUrl)
                .then(response => response.blob())
                .then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `speech-audio-${Date.now()}.mp3`;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                })
                .catch(err => {
                    console.error('下载失败:', err);
                    alert('音频下载失败，请重试');
                });
        }
    },
    watch: {
        // 当 audioUrl 变化（重新生成语音）时，重置播放状态
        audioUrl(newVal, oldVal) {
            // 只有当audioUrl真正变化时才重置
            if (newVal !== oldVal) {
                this.isPlaying = false;
                // 使用nextTick确保 DOM 更新后再操作
                this.$nextTick(() => {
                    const audioEl = this.$refs.audioRef;
                    if (audioEl) {
                        audioEl.pause();
                        audioEl.currentTime = 0; // 回到音频开头
                        audioEl.load(); // 重新加载音频源
                    }
                });
            }
        }
    },
    template: `
        <el-card shadow="hover" style="margin: 20px;">
            <div slot="header" style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <span style="font-size: 18px; font-weight: 600;">文字转语音</span>
                    <p style="margin: 8px 0 0 0; color: #909399; font-size: 14px;">输入文字，转换为语音播放</p>
                </div>
                <el-button 
                    type="text" 
                    icon="el-icon-setting" 
                    @click="showSettings"
                    style="padding: 0;"
                >
                    设置
                </el-button>
            </div>
            
            <el-input
                v-model="inputText"
                type="textarea"
                :rows="4"
                placeholder="请输入要转换为语音的文字"
                :disabled="loading"
            ></el-input>
            
            <div style="margin-top: 20px;">
                <el-button 
                    type="primary" 
                    @click="submit"
                    :loading="loading"
                    :disabled="!inputText.trim() || loading"
                    icon="el-icon-headset"
                    style="width: 100%;"
                >
                    {{ loading ? '生成中...' : '生成语音' }}
                </el-button>
            </div>

            <!-- 错误提示 -->
            <el-alert
                v-if="error"
                :title="error"
                type="error"
                :closable="true"
                @close="error = null"
                show-icon
                style="margin-top: 20px;"
            ></el-alert>

            <!-- 语音播放区域：优化UI，显式控制播放 -->
            <div v-if="hasValidAudio" style="margin-top: 20px;">
                <el-card shadow="never" style="background-color: #f5f7fa;">
                    <div slot="header" style="display: flex; justify-content: space-between; align-items: center;">
                        <h3 style="margin: 0; font-size: 16px; font-weight: bold;">语音生成成功</h3>
                        <div style="display: flex; gap: 8px;">
                            <el-button 
                                @click="isPlaying ? pauseAudio() : playAudio()"
                                :icon="isPlaying ? 'el-icon-pause' : 'el-icon-play'"
                                type="text"
                                size="small"
                            >
                                {{ isPlaying ? '暂停' : '播放' }}
                            </el-button>
                            <el-button 
                                @click="downloadAudio"
                                icon="el-icon-download"
                                type="primary"
                                size="small"
                            >
                                下载
                            </el-button>
                        </div>
                    </div>
                    <!-- 禁用自动播放，用 ref 引用 -->
                    <audio 
                        ref="audioRef"
                        :src="audioUrl" 
                        controls 
                        style="width: 100%;"
                        autoplay="false"
                        preload="none"
                        @ended="onAudioEnded"
                        @pause="isPlaying = false"
                        @play="isPlaying = true"
                        @loadstart="console.log('音频开始加载')"
                    >
                        您的浏览器不支持音频播放
                    </audio>
                    <div style="margin-top: 10px; color: #909399; font-size: 12px;">
                        提示：点击播放按钮开始收听，支持暂停/继续、调节音量
                    </div>
                </el-card>
            </div>
            
            <!-- 设置对话框 -->
        </el-card>
    `
};